package com.hs.dict.action;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.hs.core.action.BaseAction;
import com.hs.core.cache.DictCacheUtil;
import com.hs.core.db.DBMgr;
import com.hs.core.utils.PageParam;
import com.hs.core.utils.PageUtil;
import com.hs.dict.model.HsCode;
import com.hs.dict.service.IDictService;
@Controller  
public class DictController  extends BaseAction {
    /**
	 * 
	 */
	private static final long serialVersionUID = -354434172898440670L;
	private static final Logger logger = Logger.getLogger(DictController.class);
	private IDictService dictService;
	 @Autowired  
	public void setDictService(IDictService dictService) {
		this.dictService = dictService;
	}
	 /**
	  * 数据字典列表
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/dict/listDict.do")   
	public ModelAndView listDict(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		PageParam pageParam = new  PageParam(request,"dict/listDict.do");
		StringBuffer buffer = new StringBuffer();
 
		/** 排序部分*/
		StringBuffer orderByStr = new StringBuffer(" ");
		//	//排序部分
		String orderName = request.getParameter("orderName");
		String orderNum = request.getParameter("orderNum"); 
		 if(StringUtils.isNotBlank(orderName)){
		    	if("1".equals(orderNum)){
		    		orderByStr.append(orderName).append(" asc");
		    	}
		    	if("2".equals(orderNum)){
		    		orderByStr.append(orderName).append(" desc");
		    	}
		    }else{
		    	orderByStr.append("a.dicttype").append(" desc");
		    	orderName = "a.dicttype";
		    	orderNum = "2";
		    }
		 request.setAttribute("orderName", orderName); 
		 request.setAttribute("orderNum", orderNum); 
		 pageParam.getConditionMap().put("orderName", orderName);
		 pageParam.getConditionMap().put("orderNum", orderNum);
		 
		 /** 排序结束*/
	    
	    //排序结束
		PageUtil pageUtil = null;
		StringBuffer searchBuffer = new StringBuffer(" select a from HsCode a where 1=1 and a.youxbj=1 ");
		String dictname = request.getParameter("dictname"); 
		String dicttype = request.getParameter("dicttype"); 
		 
		if(StringUtils.isNotBlank(dictname)){
			searchBuffer.append(" and a.dictname like ?");
			pageParam.getConditionMap().put("dictname", dictname);
			request.setAttribute("dictname", dictname);
		}  
		if(StringUtils.isNotBlank(dicttype)){
			searchBuffer.append(" and a.dicttype =").append(dicttype);
			pageParam.getConditionMap().put("dicttype", dicttype);
			request.setAttribute("dicttype", dicttype);
		}  
 
		 searchBuffer.append(" order by  ").append(orderByStr);
		Map data = new HashMap();
		pageParam.setSearchSql(searchBuffer.toString());
		pageUtil = dictService.getDictList(pageParam);
		data.put("dictList", pageUtil);   
 		return new ModelAndView("common/dict/dictList",data);  
	}
	 /**
	  * 新增数据字典
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/dict/addDict.do")   
	public ModelAndView addDict(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String dictId = request.getParameter("id");
		String opertype = request.getParameter("opertype");

		Map data = new HashMap();
		if(StringUtils.isNotBlank(dictId)){
			HsCode  dictInfo = (HsCode)dictService.findByID(HsCode.class, new Long(dictId)); 
			data.put("obj", dictInfo);
		}
		if(null != opertype){
			data.put("refresh", "refresh");
		}
		return new ModelAndView("common/dict/dictInfo",data);
	}
	/**
	  * 数据字典管理页面
	  * @param request
	  * @param response
	  * @return
	  * @throws ServletException
	  * @throws IOException
	  */
	@RequestMapping("/dict/dictmanage.do")   
	public ModelAndView dictmanage(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException { 
		return new ModelAndView("common/dict/dictFrame",null);
	}
	/**
	 * 保存数据字典
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/dict/saveDict.do") 
	public ModelAndView saveDict(HttpServletRequest request,
				HttpServletResponse response) throws ServletException, IOException {
		Map data = new HashMap();
		String dictId = request.getParameter("id");
		String dictcode = request.getParameter("dictcode");
		String dictname = request.getParameter("dictname");
		String dicttype = request.getParameter("dicttype");
		String dictnum = request.getParameter("dictnum");
		String isdefault = request.getParameter("isdefault");
		if(StringUtils.isBlank(dictnum))
			dictnum = "1";
		HsCode codeInfo = null;
		if(StringUtils.isBlank(dictId)){//主键为空则判定为新增
			codeInfo = new HsCode(); 
	    }else{
	    	codeInfo = (HsCode)dictService.findByID(HsCode.class, new Long(dictId));
		}
		codeInfo.setDictcode(dictcode);
		codeInfo.setDictname(dictname);
		codeInfo.setDicttype(new Long(dicttype)); 
		codeInfo.setOrdnum(new Long(dictnum));
		codeInfo.setYouxbj(new Long(1));
		if(StringUtils.isNotEmpty(isdefault)){
			codeInfo.setIsdefault(new Long(isdefault));
		}else{
			codeInfo.setIsdefault(new Long(0));
		}
	    dictService.saveObject(codeInfo); 
	    data.put("obj", codeInfo);
	    data.put("flag", "flag");
	    DictCacheUtil.initInst(request.getSession().getServletContext());
 	    return new ModelAndView("common/dict/dictInfo",data);
	}
	
	@RequestMapping("/dict/listdicttree.do")   
	public void listdicttree(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		 
		StringBuilder builder = new StringBuilder();
		builder.append("<?xml version='1.0' encoding='UTF-8'?>\n");
		builder.append("<tree id=\"0\">\n");
		
		DBMgr dbutil = this.getDbo(request); 
		builder.append("<item text=\"").append("字典类型").append("\" open=\"1\" id=\"").append("10000").append("\">");
		builder.append("\n"); 
		List dataList = dbutil.queryList("select * from hs_code where dicttype=1 and youxbj=1 order by ordnum", null);
		for(int j=0;j<dataList.size();j++){
			Map node = (Map)dataList.get(j);
			String idNode = node.get("DICTCODE")+""; 
			builder.append("<item text=\"").append(node.get("DICTNAME")).append("\"");
			builder.append(" open=\"1\" id=\"").append(idNode).append("\" ");
			builder.append(">\n"); 
			builder.append("</item>\n");
		}
		builder.append("</item>\n"); 
		builder.append("</tree>"); 
		logger.info("builder：" + builder.toString());
		response.setCharacterEncoding("UTF-8");
    	try {
			PrintWriter w = response.getWriter(); 
			 w.println(builder.toString());
			 w.flush();
			 w.close();
		} catch (IOException e) {
			 throw e;
		} 
	}
}
